﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Common.DTO;
using Database.Exceptions;

namespace Database.Repositories
{
    public class IslandRepository : RepositoryBase<Island>, IRepository<IslandDTO>
    {

        public IslandRepository()
        {
        }

        public List<IslandDTO> GetAll()
        {
            return null;
        }

        public Guid Create(IslandDTO islandDTO)
        {
            try
            {
                var islandEntity = Mapper.Map(islandDTO);
                var id = Guid.NewGuid();
                islandEntity.Id = id;

                DbContext.IslandSet.Add(islandEntity);
                SaveChanges(1);

                return id;
            }
            catch (Exception e)
            {
                // TODO_OL: Log the Exception

                return Guid.Empty;
            }
        }

        public IslandDTO Read(Guid islandId)
        {
            try
            {
                return Mapper.Map(
                    DbContext.IslandSet.Single(
                        x => x.Id.Equals(islandId)));
            }
            catch (InvalidOperationException e)
            {
                return null;
                //throw new EntityDoesNotExistException("Island does not exist");
            }
            catch (Exception)
            {
                return null;
            }
            finally
            {
                DbContext.Database.Connection.Close();
                //DbContext.Dispose();
            }
        }


        public bool Update(IslandDTO dto)
        {
            throw new NotImplementedException();
        }

        public bool Delete(Guid id)
        {
            throw new NotImplementedException();
        }


        public bool DeleteAll()
        {
            RefreshDb();

            var allEntites = DbContext.IslandSet.ToList();
            allEntites.ForEach(delegate(Island entity)
            {
                MarkEntityForDeletion(entity);
            });
            return SaveChanges(allEntites.Count);
        }

        public override bool MarkEntityForDeletion(Island entity)
        {
            MarkEntityDependenciesForDeletion();
            DbContext.IslandSet.Remove(entity);

            return true;
        }

        protected override void MarkEntityDependenciesForDeletion()
        {

        }
    }
}
